<template>
  <view class="bg-white h-screen flex flex-col">
    <!-- 顶部导航栏 -->
    <view class="px-6 flex items-center justify-between" :style="{ paddingTop: (statusBarHeight + 48) + 'px', paddingBottom: '16px' }">
      <text class="text-xl font-bold">我的设备</text>
      <view class="flex items-center space-x-3">
        <view class="w-10 h-10 rounded-full bg-gray-100 text-gray-600 flex items-center justify-center relative" @click="goToMessages">
          <text class="fas fa-bell"></text>
          <!-- 消息红点 -->
          <view v-if="unreadCount > 0" class="absolute -top-1 -right-1 w-3 h-3 bg-red-500 rounded-full text-xs text-white flex items-center justify-center">{{ unreadCount }}</view>
        </view>
        <view class="w-10 h-10 rounded-full bg-blue-500 text-white flex items-center justify-center shadow-lg shadow-blue-200" @click="goToAddDevice">
          <text class="fas fa-plus"></text>
        </view>
      </view>
    </view>

    <!-- 设备列表 -->
    <view class="flex-1 px-6 overflow-auto">
      <!-- 空状态 -->
      <view v-if="devices.length === 0" class="flex flex-col items-center justify-center h-full">
        <view class="w-32 h-32 bg-gray-100 rounded-full flex items-center justify-center mb-6">
          <text class="fas fa-mountain text-4xl text-gray-400"></text>
        </view>
        <text class="text-gray-500 mb-6">还没有添加任何设备</text>
        <view class="bg-blue-500 text-white px-6 py-3 rounded-xl font-medium shadow-lg shadow-blue-200 hover:bg-blue-600 transition-colors" @click="goToAddDevice">
          <text>添加设备</text>
        </view>
      </view>

      <!-- 设备卡片列表 -->
      <view v-else class="space-y-4 py-4">
        <!-- 设备卡片 -->
        <view 
          v-for="device in devices" 
          :key="device.id" 
          class="bg-white rounded-2xl p-4 border border-gray-100 shadow-sm flex items-center justify-between group hover:border-blue-500 transition-colors"
          @click="enterDeviceControl(device)"
        >
          <view class="flex items-center space-x-4">
            <view class="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center">
              <text class="fas fa-mountain text-2xl text-gray-400"></text>
            </view>
            <view>
              <text class="font-medium text-gray-900">{{ device.name }}</text>
              <view class="flex items-center space-x-2 mt-1">
                <view class="w-2 h-2 rounded-full" :class="{
                  'bg-green-300': device.status === 1, // 在线状态
                  'bg-yellow-300': device.status === 2, // 忙碌状态
                  'bg-gray-300': device.status === 0  // 离线状态
                }"></view>
                <text class="text-sm text-gray-500 flex items-center">
                  {{ device.status === 0 ? '离线' : (device.status === 1 ? '在线' : '忙碌') }}
                </text>
              </view>
            </view>
          </view>
          <view class="w-10 h-10 rounded-full bg-gray-100 text-gray-500 flex items-center justify-center group-hover:bg-blue-500 group-hover:text-white transition-colors">
            <text class="fas fa-chevron-right"></text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
    import { deviceApi,messageApi } from '@/api/index.js'
	

export default {
  name: 'DeviceList',
  data() {
    return {
      statusBarHeight: 0,
      unreadCount: 0,
      devices: [],
      loading: false,
      userId: null, // 当前登录用户ID
      isFirstLoad: true // 标记是否首次加载
    }
  },
  onLoad() {
    this.initPage()
    this.loadData()
  },
  onShow() {
    // 页面显示时刷新数据，但跳过首次加载
    if (!this.isFirstLoad) {
      this.loadData()
    }
    this.isFirstLoad = false
  },
  onPullDownRefresh() {
    // 下拉刷新
    this.loadData().finally(() => {
      uni.stopPullDownRefresh()
    })
  },
  methods: {
    initPage() {
      const systemInfo = uni.getSystemInfoSync()
      
    },

    async loadData() {
      this.loading = true
	  console.log('11111')
      try {
        await Promise.all([
          this.loadDevices(),
          this.loadUnreadCount()
        ])
      } catch (error) {
        console.error('加载数据失败:', error)
        uni.showToast({
          title: '加载失败，请重试',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },

    async loadDevices() {
      
      try {

        const result = await deviceApi.getDevices()
        
        if (result.errCode === 0) {
          this.devices = result.data.map(device => ({
            id: device._id,
            deviceId: device.device_id,
            name: device.device_name,
            isOnline: device.device_status === 1 || device.device_status === 2, // 1-在线，2-忙碌都视为在线
            status: device.device_status,
            location: device.location,
            currentPattern: device.current_pattern
          }))
        } else {
          uni.showToast({
            title: result.errMsg || '获取设备列表失败',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
        throw error
      }
    },

    async loadUnreadCount() {
      if (!this.userId) return
      
      try {

        const result = await messageApi.getUnreadCount({ userId: this.userId })
        if (result.errCode === 0) {
          this.unreadCount = result.data.count || 0
        }
      } catch (error) {
        console.error('获取未读消息数量失败:', error)
        // 不影响主要功能，不抛出错误
      }
    },

    enterDeviceControl(device) {
      console.log(device)
      if (device.status === 0) {
        uni.showToast({
          title: '设备已离线，请检查网络设置',
          icon: 'none',
          duration: 2000
        })
        return
      }

      uni.navigateTo({
        url: `/pages/device/control?deviceId=${device.id}&deviceName=${encodeURIComponent(device.name)}`
      })
    },

    goToAddDevice() {
      uni.navigateTo({
        url: '/pages/device/add'
      })
    },

    goToMessages() {
      uni.navigateTo({
        url: '/pages/messages/index'
      })
    }
  }
}
</script>

<style scoped>
/* TailwindCSS 工具类样式 */
.bg-white { background-color: #ffffff; }
.bg-gray-100 { background-color: #f3f4f6; }
.bg-gray-300 { background-color: #d1d5db; }
.bg-gray-400 { background-color: #9ca3af; }
.bg-gray-500 { background-color: #6b7280; }
.bg-gray-900 { background-color: #111827; }
.bg-green-300 { background-color: #86efac; }
.bg-yellow-300 { background-color: #fcd34d; }
.bg-blue-500 { background-color: #3b82f6; }
.bg-blue-600 { background-color: #2563eb; }
.bg-red-500 { background-color: #ef4444; }

.text-white { color: #ffffff; }
.text-gray-400 { color: #9ca3af; }
.text-gray-500 { color: #6b7280; }
.text-gray-600 { color: #4b5563; }
.text-gray-900 { color: #111827; }

.text-xs { font-size: 24rpx; }
.text-sm { font-size: 28rpx; }
.text-xl { font-size: 40rpx; }
.text-2xl { font-size: 48rpx; }
.text-4xl { font-size: 72rpx; }

.font-bold { font-weight: 700; }
.font-medium { font-weight: 500; }

.h-screen { height: 100vh; }
.h-full { height: 100%; }
.h-2 { height: 16rpx; }
.h-3 { height: 24rpx; }
.h-10 { height: 80rpx; }
.h-16 { height: 128rpx; }
.h-32 { height: 256rpx; }

.w-2 { width: 16rpx; }
.w-3 { width: 24rpx; }
.w-10 { width: 80rpx; }
.w-16 { width: 128rpx; }
.w-32 { width: 256rpx; }

.flex { display: flex; }
.flex-col { flex-direction: column; }
.flex-1 { flex: 1; }
.items-center { align-items: center; }
.justify-center { justify-content: center; }
.justify-between { justify-content: space-between; }

.px-6 { padding-left: 48rpx; padding-right: 48rpx; }
.py-3 { padding-top: 24rpx; padding-bottom: 24rpx; }
.py-4 { padding-top: 32rpx; padding-bottom: 32rpx; }
.p-4 { padding: 32rpx; }
.mb-1 { margin-bottom: 8rpx; }
.mb-6 { margin-bottom: 48rpx; }
.mt-1 { margin-top: 8rpx; }

.space-x-2 > * + * { margin-left: 16rpx; }
.space-x-3 > * + * { margin-left: 24rpx; }
.space-x-4 > * + * { margin-left: 32rpx; }
.space-y-4 > * + * { margin-top: 32rpx; }

.rounded-full { border-radius: 50%; }
.rounded-xl { border-radius: 24rpx; }
.rounded-2xl { border-radius: 32rpx; }

.border { border-width: 2rpx; }
.border-gray-100 { border-color: #f3f4f6; }
.hover\:border-blue-500:hover { border-color: #3b82f6; }

.shadow-sm { box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05); }
.shadow-lg { box-shadow: 0 20rpx 50rpx -12rpx rgba(0, 0, 0, 0.25); }
.shadow-blue-200 { box-shadow: 0 8rpx 24rpx rgba(147, 197, 253, 0.3); }

.absolute { position: absolute; }
.relative { position: relative; }
.-top-1 { top: -8rpx; }
.-right-1 { right: -8rpx; }

.overflow-auto { overflow: auto; }
.transition-colors { transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out, border-color 0.15s ease-in-out; }

.group:hover .group-hover\:bg-blue-500 { background-color: #3b82f6; }
.group:hover .group-hover\:text-white { color: #ffffff; }
.hover\:bg-blue-600:hover { background-color: #2563eb; }


.home-page {
  min-height: 100vh;
  background-color: #ffffff;
  display: flex;
  flex-direction: column;
}

.nav-header {
  padding: 0 48rpx 32rpx;
  background-color: #ffffff;
}

.nav-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-top: 24rpx;
}

.nav-title {
  font-size: 40rpx;
  font-weight: bold;
  color: #000000;
}

.nav-actions {
  display: flex;
  align-items: center;
  gap: 24rpx;
}

.message-btn {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background-color: #f3f4f6;
  color: #6b7280;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.message-btn .fas {
  font-size: 32rpx;
}

.message-badge {
  position: absolute;
  top: -8rpx;
  right: -8rpx;
  width: 24rpx;
  height: 24rpx;
  background-color: #ef4444;
  border-radius: 50%;
  font-size: 20rpx;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
}

.add-btn {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background-color: #3b82f6;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 24rpx rgba(59, 130, 246, 0.3);
}

.add-btn .fas {
  font-size: 32rpx;
}

.device-content {
  flex: 1;
  padding: 0 48rpx;
  overflow: auto;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 120rpx 0;
}

.empty-icon {
  width: 256rpx;
  height: 256rpx;
  background-color: #f3f4f6;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 48rpx;
}

.empty-icon .fas {
  font-size: 96rpx;
  color: #9ca3af;
}

.empty-text {
  color: #6b7280;
  font-size: 32rpx;
  margin-bottom: 48rpx;
}

.add-device-btn {
  background-color: #3b82f6;
  color: white;
  padding: 24rpx 48rpx;
  border-radius: 24rpx;
  font-weight: 500;
  box-shadow: 0 8rpx 24rpx rgba(59, 130, 246, 0.3);
  transition: background-color 0.2s;
}

.add-device-btn:active {
  background-color: #2563eb;
}

.device-list {
  padding: 32rpx 0;
  display: flex;
  flex-direction: column;
  gap: 32rpx;
}

.device-card {
  background-color: white;
  border-radius: 32rpx;
  padding: 32rpx;
  border: 2rpx solid #f3f4f6;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  justify-content: space-between;
  transition: all 0.2s;
}

.device-card:active {
  border-color: #3b82f6;
  transform: scale(0.98);
}

.device-info {
  display: flex;
  align-items: center;
  gap: 32rpx;
}

.device-icon {
  width: 128rpx;
  height: 128rpx;
  background-color: #f3f4f6;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.device-icon .fas {
  font-size: 48rpx;
  color: #9ca3af;
}

.device-details {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.device-name {
  font-weight: 500;
  color: #111827;
  font-size: 32rpx;
}

.device-status {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.status-dot {
  width: 16rpx;
  height: 16rpx;
  border-radius: 50%;
}

.status-dot.online {
  background-color: #22c55e;
}

.status-dot.offline {
  background-color: #d1d5db;
}

.status-text {
  font-size: 28rpx;
  color: #6b7280;
}

.device-arrow {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background-color: #f3f4f6;
  color: #6b7280;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.device-card:hover .device-arrow {
  background-color: #3b82f6;
  color: white;
}

.device-arrow .fas {
  font-size: 24rpx;
}

/* Font Awesome 字体图标 */
.fas {
  font-family: "Font Awesome 6 Free", "Font Awesome 5 Free";
  font-weight: 900;
}

.fa-bell:before { content: "\f0f3"; }
.fa-plus:before { content: "\f067"; }
.fa-mountain:before { content: "\f6fc"; }
.fa-chevron-right:before { content: "\f054"; }
</style>

